package controllers

import (
	"data_summary/common/app"
	db2 "data_summary/common/db"
	models "data_summary/common/models/stat"
	"data_summary/service/dao/stat"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func AddTask(ctx *gin.Context) {
	var statTask models.StatTask
	if err := ctx.ShouldBindJSON(&statTask); err != nil {
		app.JsonResponse(ctx, http.StatusOK, app.ERROR, err.Error())
		return
	}
	statTask.CreateTime = time.DateTime
	statTask.UpdateTime = time.DateTime
	stat_db := db2.GetDb("database")
	statTaskDao := stat.NewStatTask(stat_db)
	task_id, err := statTaskDao.Update(&statTask)
	if err != nil {
		app.JsonResponse(ctx, http.StatusOK, app.ERROR, err)
		return
	}
	//设置缓存数据
	list := statTaskDao.Get(map[string]interface{}{"task_type": statTask.TaskType, "status": 1}, "id desc", 1, 1000)
	buf, err := json.Marshal(list)
	if err != nil {
		app.JsonResponse(ctx, http.StatusOK, app.ERROR, err)
	}
	redisDb := db2.GetPool()
	id_str := strconv.Itoa(statTask.TaskType)
	_, err = redisDb.Set(ctx, "stat:task:"+id_str, buf, 0).Result()
	if err != nil {
		app.JsonResponse(ctx, http.StatusOK, app.ERROR, err.Error())
	} else {
		app.JsonResponse(ctx, http.StatusOK, app.SUCCESS,
			gin.H{
				"task_id": task_id,
			},
		)
	}
}
